package com.glor.operation.common.web.security.userdetails;

import com.glor.operation.common.user.dto.UserDTO;
import com.glor.operation.common.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Created by heylear.cai on 2016/2/19.
 */
public class DefaultUserDetailsService implements UserDetailsService {

    private static final String ROLE_PREFIX = "ROLE_";

    private static final String ROLE_SPLIT = "\\s*,\\s*";

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO user = userService.findUserByUsername(username);
        if (user != null) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            StringTokenizer st = new StringTokenizer(user.getAuthorities(), ROLE_SPLIT);
            while (st.hasMoreTokens()) {
                GrantedAuthority authority = new SimpleGrantedAuthority(ROLE_PREFIX + st.nextToken());
                authorities.add(authority);
            }
            DefaultUserDetails details = new DefaultUserDetails(username, user.getPasswd(), 1 == user.getUserFlag(), true, true, true, authorities);
            details.setUserId(user.getId());
            details.setFullname(user.getFullname());
            return details;
        }
        return null;
    }
}
